const GameService = require('../services/gameService');

// 统一响应格式
const success = (data, msg = '操作成功') => ({
  code: 200,
  msg,
  data
});

const error = (msg = '操作失败', code = 500) => ({
  code,
  msg,
  data: null
});

// 获取房间列表
exports.getRoomList = (req, res) => {
  try {
    const rooms = GameService.getRoomList();
    res.json(success(rooms));
  } catch (err) {
    res.json(error(err.message));
  }
};

// 创建房间
exports.createRoom = (req, res) => {
  try {
    const { roomName, password, maxPlayers = 3 } = req.body;
    const userId = req.headers['user-id'] || 'user_' + Date.now();
    // 解码 URL 编码的用户名
    const userNameEncoded = req.headers['user-name'] || '';
    const userName = userNameEncoded ? decodeURIComponent(userNameEncoded) : '玩家' + Math.floor(Math.random() * 1000);
    
    const room = GameService.createRoom(roomName, password, maxPlayers, userId, userName);
    res.json(success(room, '房间创建成功'));
  } catch (err) {
    res.json(error(err.message));
  }
};

// 加入房间
exports.joinRoom = (req, res) => {
  try {
    const { roomId, password } = req.body;
    const userId = req.headers['user-id'] || 'user_' + Date.now();
    // 解码 URL 编码的用户名
    const userNameEncoded = req.headers['user-name'] || '';
    const userName = userNameEncoded ? decodeURIComponent(userNameEncoded) : '玩家' + Math.floor(Math.random() * 1000);
    
    const room = GameService.joinRoom(roomId, password, userId, userName);
    res.json(success(room, '加入房间成功'));
  } catch (err) {
    res.json(error(err.message));
  }
};

// 离开房间
exports.leaveRoom = (req, res) => {
  try {
    const { roomId } = req.body;
    const userId = req.headers['user-id'];
    
    GameService.leaveRoom(roomId, userId);
    res.json(success(null, '离开房间成功'));
  } catch (err) {
    res.json(error(err.message));
  }
};

// 获取房间详情
exports.getRoomDetail = (req, res) => {
  try {
    const { roomId } = req.query;
    const room = GameService.getRoomDetail(roomId);
    res.json(success(room));
  } catch (err) {
    res.json(error(err.message));
  }
};

// 准备/取消准备
exports.toggleReady = (req, res) => {
  try {
    const { roomId } = req.body;
    const userId = req.headers['user-id'];
    
    const room = GameService.toggleReady(roomId, userId);
    res.json(success(room, '状态切换成功'));
  } catch (err) {
    res.json(error(err.message));
  }
};

// 开始游戏
exports.startGame = (req, res) => {
  try {
    const { roomId } = req.body;
    const userId = req.headers['user-id'];
    
    const gameState = GameService.startGame(roomId, userId);
    res.json(success(gameState, '游戏开始'));
  } catch (err) {
    res.json(error(err.message));
  }
};

// 亮黑A
exports.showBlackA = (req, res) => {
  try {
    const { roomId, cardId } = req.body;
    const userId = req.headers['user-id'];
    
    const result = GameService.showBlackA(roomId, userId, cardId);
    res.json(success(result, '亮黑A成功'));
  } catch (err) {
    res.json(error(err.message));
  }
};

// 反红A
exports.showRedA = (req, res) => {
  try {
    const { roomId, cardId } = req.body;
    const userId = req.headers['user-id'];
    
    const result = GameService.showRedA(roomId, userId, cardId);
    res.json(success(result, '反红A成功'));
  } catch (err) {
    res.json(error(err.message));
  }
};

// 出牌
exports.playCards = (req, res) => {
  try {
    const { roomId, cards } = req.body;
    const userId = req.headers['user-id'];
    
    const result = GameService.playCards(roomId, userId, cards);
    res.json(success(result, '出牌成功'));
  } catch (err) {
    res.json(error(err.message));
  }
};

// 过牌
exports.passCards = (req, res) => {
  try {
    const { roomId } = req.body;
    const userId = req.headers['user-id'];
    
    const result = GameService.passCards(roomId, userId);
    res.json(success(result, '过牌成功'));
  } catch (err) {
    res.json(error(err.message));
  }
};

// 获取游戏状态
exports.getGameStatus = (req, res) => {
  try {
    const { roomId } = req.query;
    const userId = req.headers['user-id'];
    
    const gameState = GameService.getGameStatus(roomId, userId);
    res.json(success(gameState));
  } catch (err) {
    res.json(error(err.message));
  }
};

// 获取最近一起玩过的好友列表
exports.getRecentFriends = (req, res) => {
  try {
    const userId = req.headers['user-id'];
    
    if (!userId) {
      return res.json(error('请先登录'));
    }
    
    const friends = GameService.getRecentFriends(userId);
    res.json(success(friends));
  } catch (err) {
    res.json(error(err.message));
  }
};

// 调试接口：获取所有房间详情（包括密码）
exports.debugRooms = (req, res) => {
  try {
    const rooms = GameService.debugGetAllRooms();
    res.json(success(rooms));
  } catch (err) {
    res.json(error(err.message));
  }
};
